from flask import Blueprint, request, jsonify
from models import Course, User, db
from utils import format_response
from decorators import teacher_required, admin_required
from flask_jwt_extended import jwt_required, get_jwt_identity

courses_bp = Blueprint('courses', __name__)

@courses_bp.route('/', methods=['GET'])
@jwt_required()
def get_courses():
    """获取所有课程"""
    try:
        # 获取查询参数
        status = request.args.get('status', 'active')
        teacher_id = request.args.get('teacher_id')
        
        # 构建查询
        query = Course.query.filter(Course.status == status)
        
        if teacher_id:
            query = query.filter(Course.teacher_id == teacher_id)
        
        courses = query.all()
        return jsonify(format_response([course.to_dict() for course in courses]))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@courses_bp.route('/<int:course_id>', methods=['GET'])
@jwt_required()
def get_course(course_id):
    """获取指定课程"""
    try:
        course = Course.query.get(course_id)
        if not course:
            return jsonify(format_response(message="课程不存在", code=404)), 404
        return jsonify(format_response(course.to_dict()))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@courses_bp.route('/', methods=['POST'])
@teacher_required
def create_course():
    """创建课程"""
    try:
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        name = data.get('name')
        code = data.get('code')
        description = data.get('description')
        
        if not name or not code:
            return jsonify(format_response(message="课程名称和代码不能为空", code=400)), 400
        
        # 检查课程代码是否已存在
        if Course.query.filter_by(code=code).first():
            return jsonify(format_response(message="课程代码已存在", code=400)), 400
        
        new_course = Course(
            name=name,
            code=code,
            description=description,
            teacher_id=current_user_id,
            status=data.get('status', 'active')
        )
        
        db.session.add(new_course)
        db.session.commit()
        
        return jsonify(format_response(new_course.to_dict(), "课程创建成功"))
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@courses_bp.route('/<int:course_id>', methods=['PUT'])
@teacher_required
def update_course(course_id):
    """更新课程"""
    try:
        course = Course.query.get(course_id)
        if not course:
            return jsonify(format_response(message="课程不存在", code=404)), 404
        
        # 检查权限：只有课程创建者或管理员可以修改
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        if course.teacher_id != current_user_id and current_user.role != 'admin':
            return jsonify(format_response(message="没有权限修改此课程", code=403)), 403
        
        data = request.get_json()
        
        if 'name' in data:
            course.name = data['name']
        
        if 'code' in data:
            # 检查课程代码是否已被其他课程使用
            existing_course = Course.query.filter_by(code=data['code']).first()
            if existing_course and existing_course.id != course_id:
                return jsonify(format_response(message="课程代码已存在", code=400)), 400
            course.code = data['code']
        
        if 'description' in data:
            course.description = data['description']
        
        if 'status' in data:
            course.status = data['status']
        
        db.session.commit()
        return jsonify(format_response(course.to_dict(), "课程更新成功"))
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@courses_bp.route('/<int:course_id>', methods=['DELETE'])
@teacher_required
def delete_course(course_id):
    """删除课程"""
    try:
        course = Course.query.get(course_id)
        if not course:
            return jsonify(format_response(message="课程不存在", code=404)), 404
        
        # 检查权限：只有课程创建者或管理员可以删除
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        if course.teacher_id != current_user_id and current_user.role != 'admin':
            return jsonify(format_response(message="没有权限删除此课程", code=403)), 403
        
        # 软删除：将状态设置为inactive
        course.status = 'inactive'
        db.session.commit()
        
        return jsonify(format_response(message="课程删除成功"))
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@courses_bp.route('/my-courses', methods=['GET'])
@teacher_required
def get_my_courses():
    """获取当前教师的课程"""
    try:
        current_user_id = get_jwt_identity()
        courses = Course.query.filter_by(teacher_id=current_user_id).all()
        return jsonify(format_response([course.to_dict() for course in courses]))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@courses_bp.route('/stats', methods=['GET'])
@teacher_required
def get_course_stats():
    """获取课程统计信息"""
    try:
        current_user_id = get_jwt_identity()
        
        # 获取当前教师的课程统计
        total_courses = Course.query.filter_by(teacher_id=current_user_id).count()
        active_courses = Course.query.filter_by(teacher_id=current_user_id, status='active').count()
        
        stats = {
            'total': total_courses,
            'active': active_courses
        }
        
        return jsonify(format_response(stats))
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500
